import { todoStore } from '../lib/data-store'
import { Todo, CreateTodoRequest, UpdateTodoRequest, TodoQuery } from '@data/todo'
import { v4 as uuidv4 } from 'uuid'

export class TodoService {
  // 生成新的sortOrder
  private async generateSortOrder(groupId?: string): Promise<number> {
    const todos = await todoStore.findAll()
    const groupTodos = todos.filter((todo) => !todo.deleted && todo.groupId === groupId)
    return groupTodos.length > 0 ? Math.max(...groupTodos.map((t) => t.sortOrder)) + 1 : 1
  }

  // 获取Todo列表
  async getTodos(query: TodoQuery = {}): Promise<Todo[]> {
    const todos = await todoStore.findAll()

    return todos
      .filter((todo) => {
        // 基础过滤
        if (query.deleted !== undefined && todo.deleted !== query.deleted) {
          return false
        }

        if (query.completed !== undefined && todo.completed !== query.completed) {
          return false
        }

        if (query.groupId !== undefined && todo.groupId !== query.groupId) {
          return false
        }

        if (query.priority && todo.priority !== query.priority) {
          return false
        }

        // 标签过滤
        if (query.tags && query.tags.length > 0) {
          const hasMatchingTag = query.tags.some((tag) => todo.tags.includes(tag))
          if (!hasMatchingTag) {
            return false
          }
        }

        // 搜索过滤
        if (query.search) {
          const searchLower = query.search.toLowerCase()
          const titleMatch = todo.title.toLowerCase().includes(searchLower)
          const descMatch = todo.description?.toLowerCase().includes(searchLower)
          if (!titleMatch && !descMatch) {
            return false
          }
        }

        // 日期过滤
        if (query.startDate || query.endDate) {
          const todoDate = new Date(todo.createdAt)
          if (query.startDate && todoDate < new Date(query.startDate)) {
            return false
          }
          if (query.endDate && todoDate > new Date(query.endDate)) {
            return false
          }
        }

        return true
      })
      .sort((a, b) => a.sortOrder - b.sortOrder)
  }

  // 根据ID获取Todo
  async getTodoById(id: string): Promise<Todo | null> {
    const todo = await todoStore.findById(id)
    return todo || null
  }

  // 创建Todo
  async createTodo(data: CreateTodoRequest): Promise<Todo> {
    const now = new Date().toISOString()
    const sortOrder = await this.generateSortOrder(data.groupId)

    const todo: Todo = {
      id: uuidv4(),
      title: data.title,
      description: data.description,
      completed: false,
      priority: data.priority || 'none',
      tags: data.tags || [],
      groupId: data.groupId,
      sortOrder,
      createdAt: now,
      updatedAt: now,
      dueDate: data.dueDate,
      deleted: false,
    }

    return await todoStore.create(todo)
  }

  // 更新Todo
  async updateTodo(id: string, data: UpdateTodoRequest): Promise<Todo | null> {
    const existing = await todoStore.findById(id)
    if (!existing || existing.deleted) {
      return null
    }

    const updates: Partial<Todo> = {
      ...data,
      updatedAt: new Date().toISOString(),
    }

    // 如果标记为完成，记录完成时间
    if (data.completed === true && !existing.completed) {
      updates.completedAt = new Date().toISOString()
    } else if (data.completed === false) {
      updates.completedAt = undefined
    }

    return await todoStore.update(id, updates)
  }

  // 软删除Todo
  async deleteTodo(id: string): Promise<boolean> {
    const existing = await todoStore.findById(id)
    if (!existing || existing.deleted) {
      return false
    }

    await todoStore.update(id, {
      deleted: true,
      deletedAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    })

    return true
  }

  // 恢复Todo
  async restoreTodo(id: string): Promise<Todo | null> {
    const existing = await todoStore.findById(id)
    if (!existing || !existing.deleted) {
      return null
    }

    return await todoStore.update(id, {
      deleted: false,
      deletedAt: undefined,
      updatedAt: new Date().toISOString(),
    })
  }

  // 永久删除Todo
  async permanentlyDeleteTodo(id: string): Promise<boolean> {
    return await todoStore.delete(id)
  }

  // 更新排序
  async updateSortOrder(items: { id: string; sortOrder: number }[]): Promise<void> {
    const updates = items.map((item) => ({
      id: item.id,
      data: {
        sortOrder: item.sortOrder,
        updatedAt: new Date().toISOString(),
      },
    }))

    await todoStore.bulkUpdate(updates)
  }

  // 获取已删除的Todos
  async getDeletedTodos(): Promise<Todo[]> {
    return this.getTodos({ deleted: true })
  }

  // 清理过期的已删除项目 (30天)
  async cleanupDeletedTodos(): Promise<number> {
    const todos = await todoStore.findAll()
    const thirtyDaysAgo = new Date()
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)

    const toDelete = todos.filter((todo) => todo.deleted && todo.deletedAt && new Date(todo.deletedAt) < thirtyDaysAgo)

    for (const todo of toDelete) {
      await this.permanentlyDeleteTodo(todo.id)
    }

    return toDelete.length
  }
}

export const todoService = new TodoService()
